import {
    createSlice
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";

export type TPanes = {
    title:string,
    key:string,
    closable:boolean
}

export type TPage = {
    current:number,
    pageSize:number,
    total:number
}
type TCommonState = {
    panes:TPanes[],
    pageInfo:TPage,
    loading:boolean
}
const initialState:TCommonState = {
    panes:[
        {
            title:"主页",
            key:"/",
            closable:false
        }
    ],
    pageInfo:{
        current:1,
        pageSize:1,
        total:1
    },
    loading:false
}
const commonSlice = createSlice({
    name:"common",
    initialState,
    reducers:{
        changeTitle(state,{payload}){
             const info:TPanes = state.panes.find((v:any)=>v.key === payload.key)as TPanes;
                info.title  = payload.title;
        },
        changeLoading(state,{payload}){
          state.loading = payload
        },
        changePageInfo(state,{payload}){
          state.pageInfo = payload
        },
        addPanes(state,{payload}){
            const info:TPanes = state.panes.find((v:TPanes)=>v.key === payload.key) as  TPanes
            if(!info){
                state.panes.push(payload)
            }
        },
        delPanes(state,{payload}){
            state.panes.splice(payload,1)
        },
        delPanesByKey(state,{payload}){
          const index = state.panes.findIndex((v:any)=>v.key === payload)
            state.panes.splice(index,1)
        }

    }
})
export const {addPanes,delPanes,changePageInfo,changeLoading,changeTitle,delPanesByKey} = commonSlice.actions
export const useSelectorCommon = ()=> useSelector((state:any)=>state.common)
export  default  commonSlice.reducer